package com.fary.expression.spel.support;

import com.fary.core.SpringException;
import com.fary.core.convert.ConversionService;
import com.fary.core.convert.TypeDescriptor;
import com.fary.core.convert.support.DefaultConversionService;
import com.fary.expression.TypeConverter;
import com.fary.expression.spel.SpelMessage;
import com.fary.util.Assert;

public class StandardTypeConverter implements TypeConverter {

    private final ConversionService conversionService;


    /**
     * Create a StandardTypeConverter for the default ConversionService.
     *
     * @see DefaultConversionService#getSharedInstance()
     */
    public StandardTypeConverter() {
        this.conversionService = DefaultConversionService.getSharedInstance();
    }

    /**
     * Create a StandardTypeConverter for the given ConversionService.
     *
     * @param conversionService the ConversionService to delegate to
     */
    public StandardTypeConverter(ConversionService conversionService) {
        Assert.notNull(conversionService, "ConversionService must not be null");
        this.conversionService = conversionService;
    }


    @Override
    public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return this.conversionService.canConvert(sourceType, targetType);
    }

    @Override
    public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
        try {
            return this.conversionService.convert(value, sourceType, targetType);
        } catch (SpringException ex) {
            throw new SpringException(SpelMessage.TYPE_CONVERSION_ERROR, ex);
        }
    }

}